resx, resy = 800, 600
--display:create ( 'Interactive Lua', resx, resy, 32, true )

local dm = DisplayMode ( )
dm.width = resx
dm.height = resy
dm.depth = 32
dm.windowed = true
display:set_mode ( dm )

if gui then
  gui.destroy ( )
end
require ( "gui" )

function catch ( ... )
  local sz = ""
  for i = 1, select ( '#', ... ) do
    local arg = select ( i, ... )
    local out
    if arg == true then
      out = "true"
    elseif arg == false then
      out = "false" 
    elseif arg == nil then
      out = "nil"
    else
      local type = type ( arg )
      if type == "number" or type == "string" then
        out = arg
      else
        out = type
      end
    end
    sz = sz .. out .. " "
  end
  return sz
end

function print ( ... )
  local sz = catch ( ... )
  log.text = log.text .. sz .. "\n"
end

function print_error ( error, text )
  if error == nil then
    return
  end
  if text then
    local len = string.len ( '[string"' .. text .. '"]' )
    error = string.sub ( error, len + 2 )
  end
  error = "input" .. error
  print ( error )
end

keyboard.on_press = function ( keyboard, key )
  if key == KEY_TAB then
    if gui.container then
      old_text = log.text
      old_input = input.text
      gui:destroy ( )  
    else
      gui.create ( )

      cn = Font ( )
      cn:load_system ( "Courier New", 12 )
      gui.set_style ( 'font', cn )

      log = gui.Textbox ( 10, 10, resx - 20, resy - 75, old_text )
      log:key_command ( KEY_PGDOWN )
      log.node.alpha = 0.75
      gui.container:add_child ( log )

      log.text = [[Welcome to the interactive Lua demo!
Use the "print" function to output text
Press tab to hide/show the console
]]

      input = gui.Input ( 10, resy - 40, resx - 120 )
      input:write ( old_input or "" )
      gui.container:add_child ( input )

      exec = gui.Button ( resx - 100, resy - 40, "Execute", 90 )
      gui.container:add_child ( exec )

      input.on_select = function ( input, text )
        if text == "" then
          return
        end
        log.text = log.text .. ">" .. text .. "\n"
        input:select_all ( )
        input:write ( "" )
        res = nil
        local func, error = loadstring ( text )
        if func == nil then
          print_error ( error, text )
          log:key_command ( KEY_PGDOWN )
          return
        end
        local code, error = pcall ( func )
        if code ~= true then
          print_error ( error, text )
        end
        if res then
          print ( res )
        end
        log:key_command ( KEY_PGDOWN )
      end

      exec.on_click = function ( exec )
        input.on_select ( input, input.text )
      end
      
      gui.container:set_focus ( input )
    end
  end
end

keyboard.on_press ( keyboard, KEY_TAB )
